//
//  ImagePickerViewModel.swift
//  JJImagePicker
//
//  Created by 李加建 on 2021/5/31.
//

import CoreGraphics
import Photos
import UIKit

enum ReqError: Error {
    case none
    case decode
}

class ImagePickerViewModel {
    var maxImagesCount: Int = 9
    var photoAssetsCount: Int = 9
    var selectedAlbum: AlbumModel?
    var albums: [AlbumModel] = []

    init() {}

    func fetchAssetCollections() {
        let subtypes: [PHAssetCollectionSubtype] = [.smartAlbumUserLibrary,
                                                    .smartAlbumScreenshots,
                                                    .smartAlbumFavorites,
                                                    .smartAlbumPanoramas,
                                                    .smartAlbumAnimated,
                                                    .smartAlbumSelfPortraits]

        let option = PHFetchOptions()
        option.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)
        option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        var assetCollection: [PHAssetCollection] = []
        /// 系统相册
        for subtype in subtypes {
            let collections = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subtype, options: nil)
            if let collection = collections.firstObject {
                assetCollection.append(collection)
            }
        }

        /// 自定义相册
        let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
        collections.enumerateObjects { collection, _, _ in
            assetCollection.append(collection)
        }

        for collection in assetCollection {
            let album = AlbumModel()
            album.result = PHAsset.fetchAssets(in: collection, options: option)
            album.name = collection.localizedTitle
            album.subtype = collection.assetCollectionSubtype.rawValue
            if album.count > 0 {
                albums.append(album)
            }
        }

        selectedAlbum = albums.first
    }

    var count: Int {
        selectedAlbum?.result?.count ?? 0
    }

    var albumsCount: Int {
        albums.count
    }
}

extension ImagePickerViewModel {
    func asset(for index: Int) -> PHAsset? {
        selectedAlbum?.result?[index]
    }

    func assetCollection(for index: Int) -> AlbumModel? {
        albums[safe: index]
    }

    func updateSelected(index: Int) {
        selectedAlbum = albums[safe: index]
    }

    func selectedAsset(index: Int, complete: ((Result<UIImage, ReqError>) -> Void)? = nil) {
        guard let asset = selectedAlbum?.result?[index] else {
            complete?(.failure(.none))
            return
        }

        let option = PHImageRequestOptions()
        option.resizeMode = .fast
        option.isSynchronous = true

        PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFill, options: option) { image, _ in
            if let image = image {
                complete?(.success(image))
            } else {
                complete?(.failure(.decode))
            }
        }
    }
}
